<?php
namespace app\index\controller;
use think\view;
use think\Db;
use think\Session;
use Qiniu\Auth as Auth;
use think\Cache;
class Order extends CommonController
{
    //订单管理
    public function index()
    {

        return $this->fetch();
    }
    //待审核订单管理
    public function check()
    {

        return $this->fetch();
    }

    /**
     * 待审核订单数据
     */
    public function get_order_check(){
        # 接收layui发送的limit
        if (trim($_GET['limit'])) {
            $limit = trim($_GET['limit']);
        }else{
            $limit = 15;
        }
        $pageSize = $limit;
        $page = $_GET['page'];


        $list = DB::name('order')
            ->where(array(
                'state'=>'待审核'
            ))
            ->order('uptime desc')
            ->page($page,$pageSize)
            ->select();
        //增加上用户的信息
        for($i=0;$i<count($list);$i++){
           
            //用户信息
            $user[$i] = db::name('user')
                ->field('qq,phone,wangwang,weixin')
                ->where(array(
                    'id'=>$list[$i]['user_id']
                ))->find();
            $list[$i]['user_qq'] = $user[$i]['qq'];
            $list[$i]['user_phone'] = $user[$i]['phone'];
            $list[$i]['user_weixin'] = $user[$i]['weixin'];


        }
        if($list){
            $data['code'] = '0';
            $data['msg'] = '';
            $data['count'] = count($list);
            $data['data'] = $list;
        }else{
            $data['code'] = '0';
            $data['msg'] = '暂无数据';
            $data['count'] = 0;
            $data['data'] = '';
        }

        exit(json_encode($data));
    }
    /**
     * 订单数据
     */
      public function get_order(){
          if (trim($_GET['limit'])) {
              $limit = trim($_GET['limit']);
          }else{
              $limit = 15;
          }
          $pageSize = $limit;
          $page = $_GET['page'];

          //搜索部分
          $searchParams = json_decode($_GET['searchParams'],true);
          $num = $searchParams['num'];
          $name = $searchParams['name'];
          $language = $searchParams['language'];
          $field = $searchParams['field'];
          $count = 0;
          if($num){
              $list = DB::name('order')
                  ->whereOr('num', 'like', '%' . $num . '%')
                  ->where('state','in','待接单,开发中,售后中,已完成,已取消')
                  ->order('uptime desc')
                  ->page($page,$pageSize)
                  ->select();
              $count = DB::name('order')
                  ->whereOr('num', 'like', '%' . $num . '%')
                  ->where('state','in','待接单,开发中,售后中,已完成,已取消')
                  ->count();
          }
          if($name){
              $list = DB::name('order')
                  ->whereOr('name', 'like', '%' . $name . '%')
                  ->where('state','in','待接单,开发中,售后中,已完成,已取消')
                  ->order('uptime desc')
                  ->page($page,$pageSize)
                  ->select();
              $count = DB::name('order')
                  ->whereOr('name', 'like', '%' . $name . '%')
                  ->where('state','in','待接单,开发中,售后中,已完成,已取消')
                  ->count();
          }
          if($language){
              $list = DB::name('order')
                  ->whereOr('language', 'like', '%' . $language . '%')
                  ->where('state','in','待接单,开发中,售后中,已完成,已取消')
                  ->order('uptime desc')
                  ->page($page,$pageSize)
                  ->select();
              $count = DB::name('order')
                  ->whereOr('language', 'like', '%' . $language . '%')
                  ->where('state','in','待接单,开发中,售后中,已完成,已取消')
                  ->count();
          }
          if($field){
              $list = DB::name('order')
                  ->whereOr('field', 'like', '%' . $field . '%')
                  ->where('state','in','待接单,开发中,售后中,已完成,已取消')
                  ->order('uptime desc')
                  ->page($page,$pageSize)
                  ->select();
              $count = DB::name('order')
                  ->whereOr('field', 'like', '%' . $field . '%')
                  ->where('state','in','待接单,开发中,售后中,已完成,已取消')
                  ->count();
          }
          if(!$num && !$name && !$language && !$field){
              $list = DB::name('order')
                  ->where('state','in','待接单,开发中,售后中,已完成,已取消')
                  ->order('uptime desc')
                  ->page($page,$pageSize)
                  ->select();
              $count = DB::name('order')
                  ->where('state','in','待接单,开发中,售后中,已完成,已取消')
                  ->count();
          }



          for($i=0;$i<count($list);$i++){
              $developer[$i] = db::name('developer')
                  ->field('pay,qq,phone,name')
                  ->where(array(
                  'id'=>$list[$i]['developerId']
              ))->find();
              $list[$i]['developer_name'] = $developer[$i]['name'];
              $list[$i]['developer_pay'] = $developer[$i]['pay'];
              $list[$i]['developer_qq'] = $developer[$i]['qq'];
              $list[$i]['developer_phone'] = $developer[$i]['phone'];

              $developer1[$i] = db::name('developer')
                  ->field('pay,qq,phone,name')
                  ->where(array(
                      'id'=>$list[$i]['developerId1']
                  ))->find();
              $list[$i]['developer1_name'] = $developer1[$i]['name'];
              $list[$i]['developer1_pay'] = $developer1[$i]['pay'];
              $list[$i]['developer1_qq'] = $developer1[$i]['qq'];
              $list[$i]['developer1_phone'] = $developer1[$i]['phone'];

              //用户信息
              $user[$i] = db::name('user')
                  ->field('qq,phone,wangwang,weixin')
                  ->where(array(
                      'id'=>$list[$i]['user_id']
                  ))->find();
              $list[$i]['user_qq'] = $user[$i]['qq'];
              $list[$i]['user_phone'] = $user[$i]['phone'];
              $list[$i]['user_weixin'] = $user[$i]['weixin'];


          }
          if($list){
              $data['code'] = '0';
              $data['msg'] = '';
              $data['count'] = $count;
              $data['data'] = $list;
          }else{
              $data['code'] = '0';
              $data['msg'] = '暂无数据';
              $data['count'] = 0;
              $data['data'] = '';
          }

          exit(json_encode($data));
      }
    /**
     * 项目初审
     */
    public function check_edit(){
        if($_GET){
            $map['id']  = $_GET['id'];
            $list = Db::name('order')->where($map)->find();
            //获取file
            $file = db::name('file')->where(array(
                'order_id'=>$list['id']
            ))->select();
            $list['file'] =$file ;
            $this->assign('list',$list);
        }

        return $this->fetch();
    }

    //发送审核通过通知
    function set_msg($openid,$num){
        //获取access_token
        $access_token = $this->getaccess_token();
        //这里是在模板里修改相应的变量
        $openid =$openid;


        $post_data = array(
            "touser"=>$openid, //推送给谁,openid
            "template_id"=>"Y1_O3ecWTjSQFioTqMQ2b8RwIFB_A0XGPzq7S-q2Ws4", //微信后台的模板信息id
            "page"=>"index", //下面为预约
            "miniprogram_state"=>"developer",
            "lang"=>"zh_CN",
            "data"=> array(
                "character_string2" => array(
                    "value"=>$num,
                ),
                "thing12"=>array(
                    "value"=>"您的订单已审核通过", //传的变量
                ),
                "thing11"=>array(
                    "value"=>"正在开发中",
                ),
                "thing13"=> array(
                    "value"=>"请在小程序查看具体信息",
                )
            )
        );
        $post_data = json_encode($post_data);
//        print_r($post_data);

        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$access_token}";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch, CURLOPT_POST,1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
        $data = curl_exec($ch);
        curl_close($ch);
//        var_dump($data);
//         return $data;
    }


    /**
     * 待审核订单 提交项目初审
     */
    public function up_check(){
        $admin_id = Session::get('service.id');
        if($_POST){
            //检测项目编号是否可用

            $num = Db::name('order')->where(array(
                'num'=>$_POST['num']
            ))->find();

            //获取用户openid
            $user = Db::name('user')->where(array(
                'id'=>$num['user_id']
            ))->find();


            if($num){
                return show(0,'该订单编号已经存在，请更换其他编号');
            }else{
               $_POST['admin_id'] = $admin_id;
               $_POST['state'] = '待接单';
//               更新项目内容
                $res = Db::name('order')->update($_POST);
                if($res){
                     $this->set_msg($user['openid'],$num['num']);
                    return show(1,'审核成功');
                }else{
                    return show(0,'审核失败，请重新审核');
                }
            }
        }
      
    }
    /**
     * 待审核订单  删除订单
     */
    public function check_del(){
        $admin_id = Session::get('service.id');
        if($_POST){
          
            //检测项目编号是否可用

            $num = Db::name('order')->where(array(
                'num'=>$_POST['num']
            ))->find();
            if($num){
                $_POST['admin_id'] = $admin_id;
                $_POST['state'] = '已取消';
                $_POST['id'] = $num['id'];
//               更新项目内容
                $res = Db::name('order')->update($_POST);
                if($res){

                    return show(1,'删除成功');
                }else{
                    return show(0,'删除失败，请重新删除');
                }

            }else{
                return show(0,'该订单已不存在，请核对后操作');
            }
        }
    }


    /**
     * 订单 推进
     */
    public function step(){

        if($_GET){
            $map['id']  = $_GET['id'];
            $list = Db::name('order')
                ->field('id,num,state,developerId,developerId1,admin_beizhu')
                ->where($map)->find();
            $dev1 = Db::name('developer')->where(array(
                'id'=>$list['developerId']
            ))->find();
            $dev2 = Db::name('developer')->where(array(
                'id'=>$list['developerId1']
            ))->find();
            $list['developerId'] = $dev1['phone'];
            $list['developerId1'] = $dev2['phone'];

            $this->assign('list',$list);
        }
        return $this->fetch();
    }

    /**
     * 填写技术手机号  设置为正在开发中
     */
    public function up_step(){
        if($_POST){
            //检测订单是否存在
            $order = DB::name('order')
                ->field('id')
                ->where(
                array(
                    'num'=>$_POST['num']
                )
            )->find();
            if($order){
               $developerId = db::name('developer')
                   ->where(array(
                       'phone'=>$_POST['id1']
                   ))->find();
                $developerId1 = db::name('developer')
                    ->where(array(
                        'phone'=>$_POST['id2']
                    ))->find();
               if($developerId){
                   $data['admin_beizhu'] = $_POST['admin_beizhu'];
                   $data['state'] = '开发中';
                   $data['developerId'] = $developerId['id'];
                   $data['developerId1'] =$developerId1['id'];
                   $data['id'] =$order['id'];
//               更新项目内容
                   $res = Db::name('order')->update($data);
                   if($res){
                       return show(1,'设置成功');
                   }else{
                       return show(0,'设置失败，请重新设置');
                   }
               }else{
                   return show(0,'主要技术在技术库中未查询到');
               }
            }else{
                return show(0,'订单不存在，或不是待审核状态');
            }

        }
    }

    /**
     * 设置为售后状态
     */
    public function up_step1(){
        if($_POST){
            //检测订单是否存在
            $order = DB::name('order')
                ->field('id')
                ->where(
                    array(
                        'num'=>$_POST['num']
                    )
                )->find();
            if($order){
                    $data['state'] = '售后中';
                    $data['id'] =$order['id'];
                    $res = Db::name('order')->update($data);
                    if($res){
                        return show(1,'设置成功');
                    }else{
                        return show(0,'设置失败，请重新设置');
                    }
            }else{
                return show(0,'订单不存在，或不是待审核状态');
            }

        }
    }

    /**
     * 设置为已完成状态
     */
    public function up_step2(){
        if($_POST){
            //检测订单是否存在
            $order = DB::name('order')
                ->field('id')
                ->where(
                    array(
                        'num'=>$_POST['num']
                    )
                )->find();
            if($order){
                $data['state'] = '已完成';
                $data['id'] =$order['id'];
                $res = Db::name('order')->update($data);
                if($res){
                    return show(1,'设置成功');
                }else{
                    return show(0,'设置失败，请重新设置');
                }
            }else{
                return show(0,'订单不存在，或不是待审核状态');
            }

        }
    }
    /**
     * 设置为取消状态
     */
    public function del(){
        if($_POST){
            //检测订单是否存在
            $order = DB::name('order')
                ->field('id')
                ->where(
                    array(
                        'id'=>$_POST['id']
                    )
                )->find();
            if($order){
                $data['state'] = '已取消';
                $data['id'] =$order['id'];
                $res = Db::name('order')->update($data);
                if($res){
                    return show(1,'设置成功');
                }else{
                    return show(0,'设置失败，请重新设置');
                }
            }else{
                return show(0,'订单不存在');
            }

        }
    }



    /*
     * 发送订阅消息
     */
    function getaccess_token(){

        $token = Db::name('token')
            ->where(array(
                'id'=>1
            ))
            ->find();
        if($token){
            if($token['expires']+$token['update_time']<time()){
                //appid与appsecret改成你自己的
                $appid = 'wxaeae5ec2124342f4';
                $appsecret = 'ff35487505508d87adf9e680e8bd1198';
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL,$url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
                $data = curl_exec($ch);
                curl_close($ch);
                $data = json_decode($data,true);

//                $da['id'] = 1;
                $da['access_token'] =$data['access_token'];
                $da['update_time'] = time();
                Db::name('token')->where('id', 1)->update($da);

                return $data['access_token'];
            }else{
                return $token['access_token'];
            }

        }

    }




    /**
     * see 订单详情
     */
    public function see(){
        if($_GET){
            $map['id']  = $_GET['id'];
            $list = Db::name('order')->where($map)->find();
            //获取file
            $file = db::name('file')->where(array(
                'order_id'=>$list['id']
            ))->select();
            $list['file'] =$file ;
            $this->assign('list',$list);
        }

        return $this->fetch();
    }

    /**
     * 填写首款
     */

    public function first_pay(){
        if($_GET){
            $map['id']  = $_GET['id'];
            $list = Db::name('order')->where($map)->find();
            //获取file
            $file = db::name('file')->where(array(
                'order_id'=>$list['id']
            ))->select();
            $list['file'] =$file ;
            $this->assign('list',$list);
        }

        return $this->fetch();
    }
    /**
     * 填写尾款
     */

    public function end_pay(){
        if($_GET){
            $map['id']  = $_GET['id'];
            $list = Db::name('order')->where($map)->find();
            //获取file
            $file = db::name('file')->where(array(
                'order_id'=>$list['id']
            ))->select();
            $list['file'] =$file ;
            $this->assign('list',$list);
        }

        return $this->fetch();
    }
    /**
     * 提交首款 尾款
     */
    public function up_check_pay(){
        $admin_id = Session::get('service.id');
        if($_POST){
            //检测项目编号是否可用

            $num = Db::name('order')->where(array(
                'num'=>$_POST['num']
            ))->find();
            if($num){
                $_POST['first_fee_state'] = '首款已支付';
                $res = Db::name('order')->update($_POST);
                if($res){

                    return show(1,'提交成功');
                }else{
                    return show(0,'提交失败，请重新提交');
                }

            }else{
                return show(0,'该订单编号不存在，请查证后再试');
            }
        }

    }

    public function up_check_pay1(){
        $admin_id = Session::get('service.id');
        if($_POST){
            //检测项目编号是否可用

            $num = Db::name('order')->where(array(
                'num'=>$_POST['num']
            ))->find();
            if($num){
                $_POST['end_fee_state'] = '尾款已支付';
                $res = Db::name('order')->update($_POST);
                if($res){

                    return show(1,'提交成功');
                }else{
                    return show(0,'提交失败，请重新提交');
                }

            }else{
                return show(0,'该订单编号不存在，请查证后再试');
            }
        }

    }

    /**
     * 添加待审核订单
     */
    public function add(){

        return $this->fetch();
    }
    public function up_file(){
        $id = $_GET['id'];
        $this->assign('id',$id);
        return $this->fetch();
    }

    public function add_up_file(){
        $file = request()->file('myFile');
//            var_dump($file);

        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->validate(['size'=>30000000,'ext'=>'jpg,png,gif,jpeg,doc,docx,ppt,pptx,xls,xlsx,pdf,txt,mp4,avi,mov,zip,rar,7z'])->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                // 成功上传后 获取上传信息

                $res['path'] = 'https://ck.51tuanke.com/bang/public/uploads/'.$info->getSaveName();
                $res['name'] = $info->getFilename();
                $data['name'] =  $res['name'];
                $data['path'] =   $res['path'];
                $data['order_id'] =   $_POST['order_id'];
                $data['uptime'] = date('Y-m-d H:i:s',time());
                $add = Db::name('file')->insert($data);
                $res['id'] = Db::name('order')->getLastInsID();
                echo "<script> alert('上传成功') 
                 parent.location.reload();//刷新父窗口 
                 parent.layer.closeAll();//关闭所有layer窗口
                 </script>";

            }else{
                // 上传失败获取错误信息
                echo "<script> alert('上传失败') </script>";
            }
        }
    }


    /**
     * 客服上传订单
     */
    public function up_add(){
        $data['state'] = '待审核';
        $data['uptime'] = date('Y-m-d H:i:s',time());
        $data['name'] = $_POST['name'];
        $data['content'] = $_POST['content'];
        $data['language'] = $_POST['language'];
        $data['platform'] = $_POST['platform'];
        $data['industry'] = $_POST['industry'];
        $data['field'] = $_POST['field'];
        $data['beizhu'] = $_POST['beizhu'];
        $data['deliver'] = $_POST['deliver'];


        $add = Db::name('order')->insert($data);

        if($add){
            return show(1,'新建成功，请继续添加文档');
        }else{
            return show(0,'新建失败，请重试');
        }
    }



}
